package com.ruoyi.merchant.service.impl;

import com.alibaba.nacos.common.codec.Base64;
import com.ruoyi.common.core.cg.pojo.IdCardOcr;
import com.ruoyi.common.core.cg.pojo.Image;
import com.ruoyi.merchant.service.IdCardOcrService;
import com.ruoyi.merchant.service.OcrService;
import com.ruoyi.merchant.service.PngService;
import com.ruoyi.merchant.service.SynthesisService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


@Service
@Slf4j
public class OcrServiceImpl implements OcrService {

    @Autowired
    private PngService pngService;
    @Autowired
    private IdCardOcrService idCardOcrService;
    @Autowired
    private SynthesisService synthesisService;

//    private final HttpServletRequest request;  // 注入 HttpServletRequest

//    @Autowired
//    public OcrServiceImpl(HttpServletRequest request) {
//        this.request = request;
//    }
//
//    // 获取用户ID（从请求头获取）
//    public String getUserIdFromRequestHeader() {
//        String userId = request.getHeader("User-ID");
//        if (userId == null) {
//            throw new RuntimeException("未找到用户ID");
//        }
//        return userId;
//    }

    @Override
    public IdCardOcr idCardOcr(MultipartFile file,Integer uid) {
        try {
            if (file == null || file.isEmpty()) {
                throw new RuntimeException("上传的文件不能为空");
            }

            // 图片转换为 Base64 格式的字符串
            byte[] base64 = Base64.encodeBase64(file.getBytes());
            String fileBase64 = new String(base64);

            // 获取用户ID（从请求头获取）
//            String userId = getUserIdFromRequestHeader();

            // 初始化腾讯云OCR客户端
            Credential cred = new Credential("AKIDBC2iDXGzfEe6TfibKvNeicTAi4VuIawl", "54uYzGKDtQp46vZBh3CAzJi09ENRK3bA");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "", clientProfile);

            // 创建请求对象
            IDCardOCRRequest req = new IDCardOCRRequest();
            req.setImageBase64(fileBase64);
            IDCardOCRResponse resp = client.IDCardOCR(req);

            // 处理OCR结果
            IdCardOcr idCardOcrVo = new IdCardOcr();
            if (resp != null && StringUtils.hasText(resp.getName())) {
                // 身份证正面
                idCardOcrVo.setName(resp.getName());
                idCardOcrVo.setGender("男".equals(resp.getSex()) ? "1" : "2");
                idCardOcrVo.setBirthday(DateTimeFormat.forPattern("yyyy/MM/dd").parseDateTime(resp.getBirth()).toDate());
                idCardOcrVo.setIdNumber(resp.getIdNum());
                idCardOcrVo.setAddress(resp.getAddress());
//                idCardOcrVo.setUid();

                idCardOcrService.idCardOcrSave(idCardOcrVo);

                // 保存身份证正面图片
                if (file != null) {
                    Image png = pngService.pngSave(file, file, file, file,uid);  // 只传入正面图片
                    if (png != null) {
                        idCardOcrVo.setFronturl(png.getFrontIdCard());
                    } else {
                        throw new RuntimeException("保存正面图片失败");
                    }
                }
            } else {
                // 如果没有识别到正面信息，抛出异常
                throw new RuntimeException("未识别到有效的身份证正面信息");
            }
            return idCardOcrVo;
        } catch (Exception e) {
            // 记录详细错误日志
            log.error("OCR 识别失败: " + e.getMessage(), e);
            throw new RuntimeException("OCR识别失败: " + e.getMessage(), e);
        }
    }
}

